package com.sinosoft.weixin.controller;

import com.sinosoft.weixin.controller.vo.Vo;
import com.sinosoft.weixin.service.ServiceException;
import org.apache.log4j.Logger;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import java.util.Arrays;

/**
 * Created by huzhengying on 2017/11/13.
 * 异常控制器
 */
@ControllerAdvice
public class ControllerExceptionHandler {
    private static final Logger logger = Logger.getLogger(ControllerExceptionHandler.class);

    @ExceptionHandler(ServiceException.class)
    @ResponseBody
    public Object handleServiceException(ServiceException ex) {
        logger.error(ex.getMessage(), ex);
        return Vo.fail(ex.getMessage());
    }

    /**
     * 处理请求方法不匹配问题
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseBody
    public Object handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException ex) {
        logger.debug(ex.getMessage(), ex);
        return Vo.fail(String.format("该资源只支持 %s 请求方法，而实际请求方法为 %s",
                Arrays.toString(ex.getSupportedMethods()), ex.getMethod()));
    }

    /**
     * 处理请求参数转换失败异常
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    @ResponseBody
    public Object handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException ex) {
        logger.debug(ex.getMessage(), ex);
        return Vo.fail(String.format("无法将请求参数 %s 转换成预期类型，请求参数值为 %s", ex.getName(), ex.getValue()));
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Object handleException(Exception ex) {
        logger.error(ex.getMessage(), ex);
        return Vo.fail("服务器出错！");
    }
}



